package com.yjian.dao.provider;

import com.yjian.dao.bean.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.SQL;

import java.util.List;
import java.util.Map;

/**
 * Created by xuxiaobao on 2017/9/27.
 */
public class UserProvider {
    /**
     * 根据用户uid查询用户信息
     * @param user
     * @return
     */
    public String getUserByUid(final User user) {
        return new SQL(){{
            SELECT(user.getQuery_sql());
            FROM("t_user");
            WHERE("uid=#{uid}");
       }}.toString();
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    public String saveUser(final User user) {
        return new SQL(){{
            INSERT_INTO("t_user");
            if (StringUtils.isNotEmpty(user.getUid())) {
                VALUES("uid","#{uid}");
            }
            if (StringUtils.isNotEmpty(user.getPhone())) {
                VALUES("phone", "#{phone}");
            }
            if (StringUtils.isNotEmpty(user.getPassword())) {
                VALUES("password", "#{password}");
            }
            if (user.getCreateTime() != null) {
                VALUES("createTime", "#{createTime}");
            }
        }}.toString();
    }

    /**
     * 检查手机号密码是否正确
     * @param user
     * @return
     */
    public String checkUserAndPassword(final User user) {
        return new StringBuilder().append(
            new SQL()
            .SELECT(user.getQuery_sql())
            .FROM("t_user")
            .WHERE("phone=#{phone} AND password=#{password}").toString()
        ).toString();
    }

    /**
     * 检查手机号是否已经注册
     * @param phone
     * @return
     */
    public String isExistUserPhone(final String phone) {
        SQL sql = new SQL();
        sql.SELECT("count(1)");
        sql.FROM("t_user");
        sql.WHERE("phone=#{value}");
        return sql.toString();
    }

    public String listUserByUid(Map<String, Object> param) {
        List<String> uids = (List<String>) param.get("list");
        SQL sql = new SQL();
        sql.SELECT("uid");
        sql.FROM("t_user");
        sql.WHERE("1=1");
        for (int i=0;i<uids.size();i++) {
            sql.OR().WHERE("uid = #{list["+i+"]}");
        }
        return sql.toString();
    }
}
